package com.bw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.domain.SysUser;
import com.bw.domain.SysUserRole;
import com.bw.mapper.SysUserRoleMapper;
import com.bw.service.SysUserService;
import com.bw.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author THINKAPD
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-02-28 15:08:37
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<SysUser> list2(SysUser sysUser) {
        return sysUserMapper.list2(sysUser);
    }

    @Transactional
    @Override
    public boolean mySave(SysUser sysUser) {
        try {
            //1.保存用户表--主表
            this.saveOrUpdate(sysUser);

            //2.先删除当前用户的拥有的角色 -- 即根据用户ID删除中间表
             sysUserRoleMapper.deleteByUserId(sysUser.getId());

            //3.保存到用户和角色中间表
            //获取角色ID-- 可能选了多个角色
            Integer[] rids = sysUser.getRids();
            //判断是否选中
            if(rids!=null&&rids.length>0){
                //执行批量添加
                for (Integer rid : rids) {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setUserId(sysUser.getId());
                    userRole.setRoleId(rid);
                    sysUserRoleMapper.insert(userRole);
                }

            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("保存失败"+e.getMessage());

        }

    }
}




